package com.ruoyi.cfuser.rescue.service.impl;

import com.ruoyi.cfuser.api.rescue.domain.RescueTask;
import com.ruoyi.common.map.service.MapService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.GeoOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("InitiateRescueService")
public class InitiateRescueServiceImpl {

    private final RedisTemplate redisTemplate;


    public InitiateRescueServiceImpl(@Qualifier("redisTemplate") RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Autowired
    private MapService mapService;
    @Resource
    private RescueTaskServiceImpl rescueTaskService;

    public Map<String,Object> filterId(RescueTask rescueTask) {
        Map lngLat = null;
        try {   // 获取用户起点经纬度
            lngLat = mapService.getLngLat(rescueTask.getPosition());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 添加维修任务
        rescueTaskService.insertRescueTask(rescueTask);
    System.out.println("id+"+rescueTask.getId());
        // 再根据返回的主键id查询维修任务
        RescueTask rescueTask1 = rescueTaskService.selectRescueTaskById(rescueTask.getId());
        Map<String,Object> map = new HashMap<>();
        map.put("rescueTask",rescueTask1);
        // 查找范围内的商家
        GeoOperations geoOperations = redisTemplate.opsForGeo();
        String citys = "citys";     // 用来存储商家
        Point center = new Point(Double.parseDouble(lngLat.get("lng").toString()),Double.parseDouble(lngLat.get("lat").toString()));
        Distance distance = new Distance(300, Metrics.KILOMETERS);
        Circle within = new Circle(center, distance);
        List<String> list = new ArrayList<>();
        GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults = geoOperations.radius(citys, within);
        for (GeoResult<RedisGeoCommands.GeoLocation<String>> geoResult : geoResults) {
            RedisGeoCommands.GeoLocation<String> content = geoResult.getContent();
            System.out.println("符合条件的商家id："+content.getName());
            list.add(content.getName());
        }
        map.put("shopIds",list);
        return map;
    }
}
